package com.tcwlkj.uuService.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.adapter.NotSnathchAdapter;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.OrderModel;
import com.tcwlkj.uuService.ui.NoOrderMapActivity;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.MyRefresh;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;
import com.tcwlkj.uuService.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/9/30 0030.
 */

public class NotSnatchOrder_Fragment extends BaseFragment {
    @Bind(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerView;
//    @Bind(R.id.lay_total_empty)
//    LinearLayout lay_total_empty;

    @Bind(R.id.lay_total_code)
    LinearLayout lay_total_code;
    @Bind(R.id.ivRunManCode)
    ImageView ivRunManCode;
    @Bind(R.id.ivUserCode)
    ImageView ivUserCode;

    private List<OrderModel> modelList = new ArrayList<OrderModel>();
    private NotSnathchAdapter notSnathchAdapter;
    private int pindex = 1;

    @Override
    protected int getLayout() {
        return R.layout.fragment_not_snatch;
    }

    //    @Override
//    public void setMenuVisibility(boolean menuVisible) {
//        super.setMenuVisibility(menuVisible);
//        Const.JpushTag=false;
//    }
    @Override
    protected void initView(Bundle savedInstanceState) {
        //final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        WrapContentLinearLayoutManager wrapContentLinearLayoutManager = new WrapContentLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(wrapContentLinearLayoutManager);
        notSnathchAdapter = new NotSnathchAdapter(modelList, getContext());
        MyRefresh.getInstance().getMusic(refreshLayout, false);
        recyclerView.setAdapter(notSnathchAdapter);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                mIsRefreshing = true;
                modelList.clear();
                pindex = 1;
                getNoOrder(pindex, true);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pindex++;
                getNoOrder(pindex, true);
                refreshLayout.finishLoadmore();
            }
        });
    }

    private boolean mIsRefreshing = false;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getNoOrder(pindex, false);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mIsRefreshing) {
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    public void getNoOrder(int pindex, boolean flag) {
        Call<CommonResponse<ArrayList<OrderModel>>> httpResultCall = RetrofitUtils.getRequest(getActivity(), false).orderlist(PreferencesUtils.getString(MyApp.getContext(), "userID"), -1, 1, pindex, 20);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<ArrayList<OrderModel>>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<ArrayList<OrderModel>> commonResponse = (CommonResponse<ArrayList<OrderModel>>) t;
                if (commonResponse.getTotal().equals("0")) {
//                    lay_total_empty.setVisibility(View.VISIBLE);
                    lay_total_code.setVisibility(View.VISIBLE);
                    Glide.with(getActivity()).load(PreferencesUtils.getString(getActivity(), "runManCode")).error(R.mipmap.iv_code).into(ivRunManCode);
                    Glide.with(getActivity()).load(PreferencesUtils.getString(getActivity(), "userCode")).error(R.mipmap.iv_code).into(ivUserCode);
                    Log.e("AAA", "onSuccess: " + PreferencesUtils.getString(getActivity(), "runManCode"));
                    recyclerView.setVisibility(View.GONE);
                    EventBus.getDefault().post(new EventCenter<String>(103, commonResponse.getTotal() + ""));
                    return;
                }
                if (flag && modelList.size() >= Integer.parseInt(commonResponse.getTotal())) {
                    ToastUtil.getInstance().show("没有更多数据");
                    return;
                }
//                lay_total_empty.setVisibility(View.GONE);
                lay_total_code.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                mIsRefreshing = false;
                modelList.addAll(commonResponse.getData());
                notSnathchAdapter.updateData(modelList);
                EventBus.getDefault().post(new EventCenter<String>(103, commonResponse.getTotal() + ""));
            }

            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    getNoOrder(pindex, flag);
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        super.onEventComing(eventCenter);
        if (eventCenter.getEventCode() == 111) {//抢单刷新
            modelList.clear();
            pindex = 1;
            getNoOrder(pindex, false);
        } else if (eventCenter.getEventCode() == 55) {//订单推送
//            if(recyclerView.getScrollState()==recyclerView.SCROLL_STATE_IDLE){
//                modelList.clear();
//                pindex=1;
//                getNoOrder(pindex,false);
//            }

        } else if (eventCenter.getEventCode() == 1003) {//跳转地图
            Intent intent = new Intent(getActivity(), NoOrderMapActivity.class);
            intent.putExtra("orderModel", (OrderModel) eventCenter.getData());
            startActivityForResult(intent, 1);
        } else if (eventCenter.getEventCode() == 222) {//取消订单
            modelList.clear();
            pindex = 1;
            getNoOrder(pindex, false);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            grab(data.getExtras().getString("orderId"));
        }
    }

    private void grab(String orderId) {
        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(getActivity(), true).grab(orderId, PreferencesUtils.getString(MyApp.getContext(), "userID"), 0, Tools.javabeanToJson(ChcheUtils.getInstance().getLocationModel()));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse commonResponse = (CommonResponse) t;
                EventBus.getDefault().post(new EventCenter<String>(111, commonResponse.getMessage()));
            }

            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    grab(orderId);
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
}
